package com.yusvn.scm.goods.base.controller;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Inject;
import com.jfinal.ext.cors.EnableCORS;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.yusvn.scm.common.BaseController;
import com.yusvn.scm.common.kit.RetKit;
import com.yusvn.scm.common.model.ScmPzbh;
import com.yusvn.scm.goods.base.service.ScmPzbhService;

import java.util.List;

@EnableCORS
public class ScmPzbhController extends BaseController {

    @Inject
    ScmPzbhService srv;


    public void page(){
        Page<ScmPzbh> list = srv.selectPzbhList(getKv());

        renderJson(RetKit.ok().setCount(list.getTotalRow()).setData( JSONObject.toJSON(list.getList()) ));
    }

    public void addPzbh(){

        renderJson(srv.addPzbh(getRawData()));
    }

    public void updatePzbh(){

        renderJson(srv.updatePzbh(getRawData()));
    }

    public void deletePzbh(){

        renderJson(srv.deletePzbh(getPara("id")));
    }

    public void download(){
        List<Record> list = srv.selectAll();
        String fileName = "配置补货.xlsx";
        String[][] headerAlias = { {"bh","编号"}, {"mc","名称"}, {"pz1", "值1"}
                                    ,{"pz2", "值1"}, {"pz3", "值3"},{"pz4", "值4"}
                                    ,{"pz5", "值5"}, {"pz6", "值6"},{"createtime", "创建时间"}
                                    , {"remark", "备注"} };

        exportExcel(list, fileName, headerAlias);
        renderNull();
    }
    /**
     * 配置补货导入excel
     */
    public void importExcel(){
        getFile();
        UploadFile file = null;
        try {
            file = getFile();
            if (file == null) {
                renderJson(RetKit.fail("msg", "请先选择上传文件"));
                return;
            }
            // 表名
            String tableName = "scm_pzbh";
            String mid = null;
            RetKit retKit = importExcel(file, tableName,mid);
            renderJson(retKit);
        } catch (Exception e) {
            if (e instanceof com.jfinal.upload.ExceededSizeException) {
                renderJson(RetKit.fail("msg", "文件大小超出范围"));
            } else {
                if (file != null) {
                    // 只有出现异常时才能删除，不能在 finally 中删，因为后面需要用到上传文件
                    file.getFile().delete();
                }
                renderJson(RetKit.fail("msg", e.getMessage()));
            }
            return ;
        }
    }
}
